package com.qf.edu.controller;

import com.qf.edu.service.ImgPathService;
import com.qf.edu.service.impl.ImgPathServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.filefilter.SuffixFileFilter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.List;

/**
 * @author:huayuzhuo
 * @email:2798866329@qq.com
 * @desc:头像上传控制类
 * @datatime: 2022/5/27 23:23
 */
@WebServlet("/fupLoad")
public class FupLoad extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //创建一个DiskFileItemFactory对象
        DiskFileItemFactory df = new DiskFileItemFactory();
        //设置一个文件保存的目录
        File fileDir = new File(this.getServletContext().getRealPath("\\img"));
        System.out.println(fileDir);
        if (!fileDir.exists()){
            //不存在就创建这个目录
            fileDir.mkdirs();
        }
        //设置文件的临时保存目录
        df.setRepository(fileDir);
        //文件上传的类
        ServletFileUpload servletFileUpload = new ServletFileUpload(df);
        servletFileUpload.setHeaderEncoding("utf-8");

        //声明一个集合
        List<FileItem> fileItemsList;

        try {
            //解析req数据       上面一大坨只是为了这里解析数据对象，路径可以在下面随意更改
            fileItemsList = servletFileUpload.parseRequest(req);
            for (FileItem fileItem:fileItemsList) {
                if (fileItem.isFormField()){
                    //判断为普通表单
                    resp.getWriter().println(fileItem.getFieldName() + ":" + fileItem.getString());
                } else {
                    //判断为文件类型字段
                    String outname = fileItem.getName();
                    //处理文件名,设置存储路径
                    outname = fileDir + "\\" + outname.substring(outname.lastIndexOf("\\") + 1);
                    String webname = "E:\\IdeaProjects\\Hospiatl_huayuzhuo\\web\\img" + "\\" + outname.substring(outname.lastIndexOf("\\") + 1);
                    //拼接读取相对路径
                    String img = "../img" + "/" + outname.substring(outname.lastIndexOf("\\") + 1);

                    HttpSession session = req.getSession();
                    ImgPathService imgPathService = new ImgPathServiceImpl();
                    Object name1 = session.getAttribute("name");
                    //更新数据库相对路径
                    String s = imgPathService.imgSer(img,name1.toString());
                    System.out.println(s);
                    //查询现在的相对路径
                    String path = imgPathService.getPath(name1.toString());
                    session.setAttribute("img",path);
                    //临时文件
                    File outfile = new File(outname);
                    File webfile = new File(webname);
                    //设置文件禁止上传的类型的大小
                    String[] str = new String[]{".exe",".bat"};
                    long maxSize = 3 * 1024 * 1024;
                    SuffixFileFilter suffixFileFilter = new SuffixFileFilter(str);
                    if (suffixFileFilter.accept(outfile)) {
                        resp.getWriter().println("禁止以.exe、.bat结尾的文件上传<br>");
                    } else if (fileItem.getSize() > maxSize){
                        resp.getWriter().println("文件大小超过3M，禁止上传<br>");
                    } else {
                        //创建输入流，输出流和缓冲数组
                        InputStream inputStream = fileItem.getInputStream();
                        //下载到out文件，让浏览器调用
                        FileOutputStream fileOutputStream = new FileOutputStream(outfile);
                        //下载到web文件，让本地有资源
                        FileOutputStream fileOutputStream1 = new FileOutputStream(webfile);
                        byte[] buffer = new byte[1024];
                        //存储每次读取的长度
                        int len;
                        while ((len = inputStream.read(buffer)) > 0){
                            fileOutputStream.write(buffer,0,len);
                            fileOutputStream1.write(buffer,0,len);
                        }
                        fileOutputStream1.close();
                        fileOutputStream.close();
                        inputStream.close();
                        System.out.println("上传头像通过");
                        resp.getWriter().println("头像已上传通过<br>");
                        //声明out对象，重新跳转到nurse.jsp文件
                        PrintWriter out = resp.getWriter();
                        out.print("<script>\n" +
                                "    top.location.href=\"/nurse/nurse.jsp\"\n" +
                                "</script>\n");
                        //使用下面这段代码，会让父页面里面的空白页再出现一个父页面
                        //resp.setHeader("refresh","2;URL=/nurse/nurse.jsp");
                    }
                    fileItem.delete();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
